package com.library.utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.net.URLRequest;

	public class ImagePool extends Sprite
	{
		public static const LOAD_COMPLETE:String = "ImagePool_load_complete";
		
		private var _loader:Loader;
		private var _bmpImg:Bitmap;
		
		private var _width:Number;
		private var _height:Number;
		
		public function ImagePool(width:Number, height:Number)
		{
			super();
			_width = width;
			_height = height;
			
			initImage();
		}
		
		private function initImage():void{
			_bmpImg = new Bitmap();
			this.addChild(_bmpImg);
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
		}
		
		// Event ////////////////////////////////
		private function onLoadComplete(evt:Event):void{
			// get image from loader
			if(_bmpImg.bitmapData != null){
        		_bmpImg.bitmapData.dispose();
        		_bmpImg.bitmapData = null;
        	}
        	var expectWidth:Number = _width;
        	var expectHeight:Number = _height;
        	var bmpData:BitmapData = new BitmapData(expectWidth, expectHeight);
        	var matx:Matrix = new Matrix();
        	matx.scale(expectWidth/_loader.content.width, expectHeight/_loader.content.height);
        	bmpData.draw(_loader.content, matx, null, BlendMode.LAYER, null, true);
        	_bmpImg.bitmapData = bmpData;
        	
        	dispatchEvent(new Event(LOAD_COMPLETE));
		}
		
		// public /////////////////////////
		public function get bitmap():Bitmap{
			var bmp:Bitmap = new Bitmap();
			var expectWidth:Number = _width;
        	var expectHeight:Number = _height;
        	var bmpData:BitmapData = new BitmapData(expectWidth, expectHeight);
        	var matx:Matrix = new Matrix();
        	matx.scale(expectWidth/_loader.content.width, expectHeight/_loader.content.height);
        	bmpData.draw(_loader.content, matx, null, BlendMode.LAYER, null, true);
        	bmp.bitmapData = bmpData;
        	
        	return bmp;			
		}
		
		public function set url(url:String):void{
			_loader.load(new URLRequest(url));			
		}
		
		public function dispose():void
		{
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadComplete);
			if(_bmpImg != null){				
				if(_bmpImg.bitmapData != null){
	        		_bmpImg.bitmapData.dispose();
	        		_bmpImg.bitmapData = null;
	        	}
	        	_bmpImg = null;
			}
		}
		
	}
}